package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"os/exec"
	"runtime"
	"strconv"
	"time"
)

// 角色属性
type SpiritMaster struct {
	Name         string
	HP           int
	MaxHP        int
	SoulPower    int
	MaxSoulPower int
	Skills       []Skill
	IsTrapped    int // 被控制剩余回合
}

// 技能属性
type Skill struct {
	ID          int
	Name        string
	Description string
	Damage      int
	Cost        int
	ControlProb float64 // 控制概率
}

var clear map[string]func() // 清屏功能

func init() {
	clear = make(map[string]func())
	clear["linux"] = func() {
		cmd := exec.Command("clear")
		cmd.Stdout = os.Stdout
		cmd.Run()
	}
	clear["windows"] = func() {
		cmd := exec.Command("cmd", "/c", "cls")
		cmd.Stdout = os.Stdout
		cmd.Run()
	}
}

// 清屏函数
func CallClear() {
	value, ok := clear[runtime.GOOS]
	if ok {
		value()
	}
}

// 创建角色
func createSpiritMaster(name string) *SpiritMaster {
	switch name {
	case "唐三":
		return &SpiritMaster{
			Name:         "唐三",
			HP:           1200,
			MaxHP:        1200,
			SoulPower:    600,
			MaxSoulPower: 600,
			Skills: []Skill{
				{1, "玄玉手", "单体伤害", 150, 80, 0},
				{2, "蓝银缠绕", "群体控制（60%概率）", 80, 120, 0.6},
				{3, "乱披风锤法", "高爆发伤害", 300, 200, 0},
				{4, "恢复", "回复30%生命", 0, 150, 0},
			},
		}
	case "小舞":
		return &SpiritMaster{
			Name:         "小舞",
			HP:           1000,
			MaxHP:        1000,
			SoulPower:    700,
			MaxSoulPower: 700,
			Skills: []Skill{
				{1, "腰弓", "快速连击", 120, 60, 0},
				{2, "魅惑", "单体控制（70%概率）", 50, 100, 0.7},
				{3, "八段摔", "多段伤害", 400, 250, 0},
				{4, "瞬移", "闪避下次攻击", 0, 120, 0},
			},
		}
	default:
		return nil
	}
}

// 显示角色状态
func (sm *SpiritMaster) DisplayStatus() {
	fmt.Printf("\n=== %s ===\n", sm.Name)
	fmt.Printf("HP: %d/%d\n", sm.HP, sm.MaxHP)
	fmt.Printf("魂力: %d/%d\n", sm.SoulPower, sm.MaxSoulPower)
	if sm.IsTrapped > 0 {
		fmt.Printf("[被控制 %d 回合]\n", sm.IsTrapped)
	}
}

// 显示技能列表
func (sm *SpiritMaster) ShowSkills() {
	fmt.Println("\n可用技能：")
	for _, s := range sm.Skills {
		fmt.Printf("%d. %s (%s) 伤害:%d 消耗:%d\n",
			s.ID, s.Name, s.Description, s.Damage, s.Cost)
	}
}

// 战斗系统
type BattleSystem struct {
	Round        int
	Player       *SpiritMaster
	Enemy        *SpiritMaster
	IsPlayerTurn bool
}

func (bs *BattleSystem) StartBattle() {
	rand.Seed(time.Now().UnixNano())
	scanner := bufio.NewScanner(os.Stdin)

	for {
		CallClear()
		fmt.Printf("===== 第 %d 回合 =====\n", bs.Round+1)
		bs.Player.DisplayStatus()
		bs.Enemy.DisplayStatus()

		if bs.checkBattleEnd() {
			return
		}

		if bs.IsPlayerTurn {
			bs.handlePlayerTurn(scanner)
		} else {
			bs.handleEnemyTurn()
		}

		bs.Round++
		bs.IsPlayerTurn = !bs.IsPlayerTurn
		time.Sleep(2 * time.Second)
	}
}

func (bs *BattleSystem) handlePlayerTurn(scanner *bufio.Scanner) {
	fmt.Print("\n你的回合：")
	bs.Player.ShowSkills()

	for {
		fmt.Print("选择技能编号（1-4）: ")
		scanner.Scan()
		input, err := strconv.Atoi(scanner.Text())

		if err != nil || input < 1 || input > 4 {
			fmt.Println("无效输入，请重新选择")
			continue
		}

		selectedSkill := bs.Player.Skills[input-1]
		if bs.Player.SoulPower < selectedSkill.Cost {
			fmt.Println("魂力不足！")
			continue
		}

		bs.executeSkill(bs.Player, bs.Enemy, selectedSkill)
		break
	}
}

func (bs *BattleSystem) handleEnemyTurn() {
	fmt.Printf("\n%s 的回合...\n", bs.Enemy.Name)

	// AI选择逻辑：优先使用可释放的高伤害技能
	var availableSkills []Skill
	for _, s := range bs.Enemy.Skills {
		if bs.Enemy.SoulPower >= s.Cost {
			availableSkills = append(availableSkills, s)
		}
	}

	if len(availableSkills) == 0 {
		fmt.Println("魂力不足，普通攻击！")
		damage := 50 + rand.Intn(50)
		bs.Player.HP -= damage
		fmt.Printf("造成 %d 点伤害！\n", damage)
		return
	}

	// 随机选择技能（可优化AI策略）
	selected := availableSkills[rand.Intn(len(availableSkills))]
	bs.executeSkill(bs.Enemy, bs.Player, selected)
}

func (bs *BattleSystem) executeSkill(attacker, defender *SpiritMaster, skill Skill) {
	attacker.SoulPower -= skill.Cost

	// 处理特殊技能
	switch skill.Name {
	case "恢复":
		heal := attacker.MaxHP * 30 / 100
		attacker.HP += heal
		if attacker.HP > attacker.MaxHP {
			attacker.HP = attacker.MaxHP
		}
		fmt.Printf("%s 恢复了 %d HP！\n", attacker.Name, heal)
		return
	case "瞬移":
		fmt.Printf("%s 进入闪避状态！\n", attacker.Name)
		// 下回合闪避逻辑需要额外状态处理（为简化示例暂不实现）
		return
	}

	// 普通攻击逻辑
	if rand.Float32() <= 1 {
		defender.HP -= skill.Damage
		fmt.Printf("%s 使用【%s】造成 %d 点伤害！\n",
			attacker.Name, skill.Name, skill.Damage)

		// 控制效果
		if skill.ControlProb > 0 && rand.Float64() < skill.ControlProb {
			defender.IsTrapped = 1
			fmt.Printf("%s 被控制了！\n", defender.Name)
		}
	} else {
		fmt.Printf("%s 的【%s】未命中！\n", attacker.Name, skill.Name)
	}
}

func (bs *BattleSystem) checkBattleEnd() bool {
	if bs.Player.HP <= 0 {
		fmt.Printf("\n%s 胜利！\n", bs.Enemy.Name)
		return true
	}
	if bs.Enemy.HP <= 0 {
		fmt.Printf("\n%s 胜利！\n", bs.Player.Name)
		return true
	}

	// 处理控制状态
	if bs.IsPlayerTurn && bs.Player.IsTrapped > 0 {
		fmt.Printf("\n%s 被控制无法行动！\n", bs.Player.Name)
		bs.Player.IsTrapped--
		return false
	}
	if !bs.IsPlayerTurn && bs.Enemy.IsTrapped > 0 {
		fmt.Printf("\n%s 被控制无法行动！\n", bs.Enemy.Name)
		bs.Enemy.IsTrapped--
		return false
	}
	return false
}

func main() {
	CallClear()
	fmt.Println("===== 斗罗大陆魂师对决 =====")
	fmt.Println("选择你的魂师：")
	fmt.Println("1. 唐三（控制/恢复型）")
	fmt.Println("2. 小舞（敏捷/爆发型）")

	scanner := bufio.NewScanner(os.Stdin)
	var player *SpiritMaster

	for {
		fmt.Print("输入选择（1-2）: ")
		scanner.Scan()
		input, err := strconv.Atoi(scanner.Text())

		if err == nil && (input == 1 || input == 2) {
			if input == 1 {
				player = createSpiritMaster("唐三")
			} else {
				player = createSpiritMaster("小舞")
			}
			break
		}
		fmt.Println("无效输入，请重新选择")
	}

	enemy := createSpiritMaster("小舞")
	if player.Name == "小舞" {
		enemy = createSpiritMaster("唐三")
	}

	battle := &BattleSystem{
		Player:       player,
		Enemy:        enemy,
		IsPlayerTurn: rand.Intn(2) == 0, // 随机先手
	}

	battle.StartBattle()
}
